package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.interfaces.MemberService;
import cn.itcast.pojo.Member;
import cn.itcast.pojo.Result;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author: peterChen
 * @date: 2019/8/16 14:59
 * @description: TODO
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("login")
public class LoginController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;


    /**
     * 提交快速登录数据
     * @param map
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request, HttpServletResponse response){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //获取redis中缓存的验证码
        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //比较验证码
        if(ObjectUtils.isEmpty(redisCode) || !redisCode.equalsIgnoreCase(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //验证码校验通过，查询该用户是否是会员
        Member member = memberService.findByTelephone(telephone);
        if(ObjectUtils.isEmpty(member)){
            //用户不存在，自动注册会员
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }

        //该用户为会员，将手机号保存到cookie中
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        //设定路径
        cookie.setPath("/");
        //设定有效时间
        cookie.setMaxAge(5*60*60);
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);


    }

}
